<?php


namespace App\Services\Customer;

use App\Common\Tools;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Customer\Address;
use App\Params\H5\AddressUpdateParams;
use App\Repository\AddressRepository;
use App\Repository\CustomerRepository;
use App\Services\BaseService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

/**
 * 授权相关业务类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Http\Services
 */
class AddressService extends BaseService
{
    /**
     * 获取客户收货地址列表
     *
     * @param array $filter
     * @return
     */
    public function getList(array $filter = [])
    {
        $address = AddressRepository::getInstance()->getList($filter);
        return $this->toSimpleList($address);
    }

    /**
     * 获取客户地址
     *
     * @param $addressId
     * @param int $customerId
     * @return
     */
    public function get($addressId, $customerId = 0)
    {
        return AddressRepository::getInstance()->getById($addressId);
    }

    /**
     * 删除客户地址
     *
     * @param int $addressId
     * @param int $customerId
     * @return mixed
     */
    public function delete(int $addressId, $customerId = 0)
    {
        $addressModel = Address::query()->where('address_id', $addressId);
        if(!empty($customerId)) {
            $addressModel->where('customer_id', $customerId);
        }
        return $addressModel->delete();
    }

    /**
     * 设置默认地址
     *
     * @param int $addressId
     * @param int $customerId
     * @return bool
     */
    public function setDefault(int $addressId, int $customerId = 0)
    {
        return AddressRepository::getInstance()->setDefault($addressId, $customerId);
    }

    /**
     * 保存收货地址
     *
     * @param AddressUpdateParams $params
     * @return int|mixed
     * @throws BusinessException
     */
    public function update(AddressUpdateParams $params)
    {
        $region = Tools::parseRegion($params->getRegion());
        $customer = CustomerRepository::getInstance()->getById($params->getCustomerId());
        $data = [
            'customer_id' => $params->getCustomerId(),
            'customer_name' => $customer->nickname,
            'contact_name' => $params->getName(),
            'mobile' => $params->getMobile(),
            'region_id' => $region['region_id'],
            'region' => $region['region'],
            'is_default' => 0,
            'full_address' => $params->getStreet()
        ];
        return AddressRepository::getInstance()->save($data, $params->getAddressId());
    }

    /**
     * 获取客户默认地址
     *
     * @param int $customerId
     * @return
     */
    public function getDefault(int $customerId)
    {
        // 查询默认地址
        $address = AddressRepository::getInstance()->getByCustomerId($customerId, 1);
        return is_null($address) ? 0 : $address->address_id;
    }
}
